import axios, {
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosInstance
} from 'axios'
// import { ElMessage } from 'element-plus'
// import router from '@/router'
import qs from 'qs'
import Dialog from '@/components/dialog/dialog'
// import storage from '@/utils/system/storage'
import UserStore from "@/store/UserStore";

// TODO 待国际化
const TOKEN_INVALID = 'Token invalid, please try again later'
const OPERATE_ERROR = 'Operate error, please try again later'
const INTERNAL_SERVER_ERROR = 'internal server error'

// @ts-ignore
const baseURL: any = import.meta.env.VITE_APP_BASE_URL

const service: AxiosInstance = axios.create({
  baseURL: baseURL,
  // timeout: 10000,
  timeout: 100000,

  // 本项目设置请求内容格式为application/x-www-form-urlencoded，axios默认是json格式
  headers: {
    'content-type': 'application/x-www-form-urlencoded' //配置请求头
  }
})

// 请求前的统一处理
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
      // qs序列化
      config.data = qs.stringify(config.data)
    }

    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    const userStore = UserStore()
    console.log('store token:', userStore.token)
    console.log('isToken:', isToken)
    // JWT鉴权处理
    if (isToken) {
      // @ts-ignore
      config.headers['apiToken'] = ''
    } else if (userStore.token && !isToken) {
      // @ts-ignore
      // config.headers['apiToken'] = userStore.token
      config.headers['apiToken'] = 'b0b3970464e94332b64e36e5386cf691'
    }
    return config
  },
  (error: AxiosError) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, data, message } = response.data
    switch (code) {
      case 200:
        return data
      case 401:
        Dialog(TOKEN_INVALID)

        // setTimeout(() => {
        //   store
        //     .dispatch('user/logout')
        //     .then(() => {
        //       router.replace(`/login/${storage.getItem('lang')}`)
        //     })
        //     .catch((err: any) => {
        //       console.log(err)
        //     })
        // }, 3000)
        return Promise.reject(TOKEN_INVALID)
      case 500:
        Dialog(message)
        return Promise.reject(INTERNAL_SERVER_ERROR)
      default:
        Dialog(message || OPERATE_ERROR)
        return Promise.reject(message || OPERATE_ERROR)
    }
  },
  (error: AxiosError) => {
    console.log(error)
    return Promise.reject(error)
  }
)

/*
 * options 请求配置
 */
function request(options: any) {
  options.method = options.method || 'get'
  // 统一请求method
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }

  if (import.meta.env.MODE === 'production') {
    // @ts-ignore
    service.defaults.baseURL = import.meta.env.VITE_APP_BASE_URL
  } else {
    // @ts-ignore
    service.defaults.baseURL =
      import.meta.env.MOCK === true
        ? import.meta.env.VITE_MOCK_BASE_URL
        : import.meta.env.VITE_APP_BASE_URL
  }

  return service(options)
}

export default request
